package dormouse.vfs.ui;

/**
 * <p>Title: Ammonite</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2001</p>
 * <p>Company: Kymerix</p>
 * @author Mark Fortner
 * @version 1.0
 */
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.util.EventObject;

import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellEditor;
import javax.swing.tree.TreePath;

public class ImmediateEditor extends DefaultTreeCellEditor {

    private FileNodeRenderer renderer;

    public ImmediateEditor(JTree tree,
            FileNodeRenderer renderer,
            FileNodeEditor editor) {
        super(tree, renderer, editor);
        this.renderer = renderer;
    }

    protected boolean canEditImmediately(EventObject e) {
        boolean rv = false;  // rv = return value

        if (e instanceof MouseEvent) {
            MouseEvent me = (MouseEvent) e;
            rv = inCheckBoxHitRegion(me);
        }
        return rv;
    }

    public boolean shouldSelectCell(EventObject e) {
        boolean rv = false;  // only mouse events

        if (e instanceof MouseEvent) {
            MouseEvent me = (MouseEvent) e;
            TreePath path = tree.getPathForLocation(me.getX(),
                    me.getY());
            FileNode node = (FileNode) path.getLastPathComponent();

            rv = node.isLeaf() || !inCheckBoxHitRegion(me);
        }
        return rv;
    }

    public boolean inCheckBoxHitRegion(MouseEvent e) {
        TreePath path = tree.getPathForLocation(e.getX(),
                e.getY());
        FileNode node = (FileNode) path.getLastPathComponent();
        boolean rv = false;

        if (node.isDirectory()) {
            // offset and lastRow DefaultTreeCellEditor
            // protected members

            Rectangle bounds = tree.getRowBounds(lastRow);
            Dimension checkBoxOffset =
                    renderer.getCheckBoxOffset();

            bounds.translate(offset + checkBoxOffset.width,
                    checkBoxOffset.height);

            rv = bounds.contains(e.getPoint());
        }
        return rv;
    }
}